<?php
class MulteController extends AppController {
    var $helpers = array ('Html','Form');
    var $name = 'Multe'; // riferimento alla cartella delle view

    public function beforeFilter(){
  
  		parent::beforeFilter();
    	
/*		if ($this->Session->read("user")==null) {
			$this->Session->setFlash("Sessione scaduta!");
			$this->redirect("/Login");
		}
*/		
    	//It’s a handy place to check for an active session or inspect user permissions.
    	Controller::loadModel('Multa');
		
    }
    
	
	public function beforeRender(){
		if(isset($this->viewVars['multe'])){
			foreach ($this->viewVars['multe'] as $chiave=>$multa) {
				$ret = Multa::getDescrizioneStato($multa['Multa']['stato']);
				$this->viewVars['multe'][$chiave]['Multa']['stato']=$ret;
			} 
		}
	}
    
    public function index() {
    	
		if (!isset($this->multe)) {
	    	//$this->loadModel('Multa');
	    	$multe=$this->Multa->find('all');

		
	        $this->set('multe', $multe);

		}

    }
	
    public function view($id='0') {

		$this->Multa->id = $id;
		$multa = $this->Multa->read();
		$this->set('STATI', Multa::$STATI);
		if ($multa!=null) {
			$this->set('multa', $multa);
		} else {
			$this->Session->setFlash('Multa inesistente');
			$this->set('multa',$multa);
		}

		
    }

    public function ricerca() {
    	
		$this->set('title_for_layout', 'Ricerca multe');

    	//la classe User è stata già istanziata dal controller perche abbiamo seguito le regole di denominazione di cake
    	//if ($id == null || !isset($id)) {
		//	$this->redirect("/users/view");
    	//} else {
			if (isset($this->request->data['targa'])) {
				if ($this->request->data['targa']=='') {
					$this->Session->setFlash('Inserire la targa');
					return;
				}
    			$targa = $this->request->data['targa'];
				//$this->Multa->targa = $targa;
				//$multe = $this->Multa->find('list', array('conditions' => array('targa' => $targa)));
				$this->set('multe', $this->Multa->find('all', array('conditions' => array('targa' => $targa))));
				//$this->redirect("/multe/index");
				$this->render('/multe/index');
				//$this->render('/multe/log');
			}
		//}
    }
	

    public function add() {
		$this->redirect("/multe/view");
    }

    public function save() {
		//$this->User->read(null,$this->params['ID']);
		//$this->User->set('LOGIN', $this->params['LOGIN']);
		$this->Multa->read(null,$this->request->data['id']);
		$this->Multa->set('foto_id', $this->request->data['foto']);
		$this->Multa->set('targa', $this->request->data['targa']);
		$this->Multa->set('via', $this->request->data['via']);
		$this->Multa->set('comune', $this->request->data['comune']);
		$this->Multa->set('infrazione', $this->request->data['infrazione']);
		$this->Multa->set('note', $this->request->data['note']);
		$this->Multa->set('agente_id', $this->request->data['agente']);
		$this->Multa->set('importo', $this->request->data['importo']);
		$this->Multa->set('stato', $this->request->data['stato']);
		$this->Multa->save();
		$this->Session->setFlash('Multa Saved!');
		$this->redirect("/multe");
    }
	

    public function delete($id='') {
		
		if ($id=='')
			$id = $this->request->data['id'];
		$this->Multa->delete($id);
		$this->Session->setFlash('Multa Deleted!');
		$this->redirect("/multe");

    }

	public function paga($id) {
		$this->inviaMailPagamento($id);		
	}
	
	public function inviaMailPagamento($id) {
		
		App::uses('CakeEmail', 'Network/Email');
		$this->email = new CakeEmail("gmail");
		$this->email->to("postmaster@scommesselivesportive.com");
		$this->email->subject("PAGA:".$id);
		$msg = "Pagamento multa in oggetto.";
		if ( $this->email->send($msg) ) {
        	$this->Session->setFlash(__('Inviata mail di pagamento avvenuto!',true));
        } else {
        	$this->Session->setFlash(__('An error occurred while sending mail.',true));
        }
		$this->redirect("/Multe/index");
		
	}
	
	public function verificaPagamenti($filtro=null) {
		
		$hostname = '{mail.scommesselivesportive.com/pop3:110}INBOX';
		$username = 'postmaster@scommesselivesportive.com';
		$password = 'maxdata';

		
		/* try to connect */
		$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());
		
		// print_r($inbox);die;
		
				
		/* grab emails */
		$emails = imap_search($inbox,$filtro);
		
		
		/* if emails are returned, cycle through each... */
		if($emails) {
			
			/* begin output var */
			$output = '';
			
			/* put the newest emails on top */
			rsort($emails);

			
			/* for every email... */
			foreach($emails as $email_number) {
				
				/* get information specific to this email */
				$overview = imap_fetch_overview($inbox,$email_number,0);
				// $header = imap_header($inbox, $email_number);
				
			// print_r($overview);print_r("<br>");print_r($header);die;
				
				
				// $message = imap_fetchbody($inbox,$email_number,2);
				
				// verifico che il messaggio non sia stato letto
				print_r($overview[0]->subject . ' ' . $overview[0]->seen);die;
				if($overview[0]->seen=='0') {
					CakeLog::write('debug', 'subject ' . $overview[0]->subject);
					$this->parseSubject($overview[0]->subject);
					
				}


				/* output the email header information */
				// $output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
				// $output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
				// $output.= '<span class="from">'.$overview[0]->from.'</span>';
				// $output.= '<span class="date">on '.$overview[0]->date.'</span>';
				// $output.= '</div>';
				
				/* output the email body */
				// $output.= '<div class="body">'.$message.'</div>';
			}
			
			// echo $output;
		} 
		
		/* close the connection */
		imap_close($inbox);
		
		$this->redirect('/Multe');
		
	}

	public function parseSubject($subject) {
		
		$ret = split(":", $subject);
		if ($ret[0]=="PAGA") {
			$idMulta=$ret[1];
			CakeLog::write('debug', 'comando ' . $ret[0] . ' id ' . $idMulta);
			$this->cambiaStatoMulta($idMulta, "P");	
		}
		// print_r($ret);die;		
		
		
	}
	
	function cambiaStatoMulta($idMulta,$stato) {
		// print_r($this->Multa->read(null,$idMulta));die;
		$ret=$this->Multa->read(null,$idMulta);
		// print_r($ret);die;
		// CakeLog::write('debug', 'ritorno read ' . $this->Multa);
		if (is_array($ret) && $ret['Multa']['id'] == $idMulta && $ret['Multa']['stato'] == 'D') {
			$this->Multa->set('stato', $stato);
			$this->Multa->save();
			$this->Session->setFlash('Multa  ' . $idMulta . ' pagata');
		}
	} 
	

}
?>